package com.example.mymusic.utils;

import android.content.ContentResolver;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

import com.example.mymusic.app.MyApp;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

public class Music {
    public static ArrayList<String> pathList = new ArrayList<>();//音乐路径
    public static ArrayList<String> nameList = new ArrayList<>();//存放音乐名称

    public static MediaPlayer mediaPlayer = new MediaPlayer();//音乐播放器

    public static int currentPosition = 0;//当前播放的音乐是第几首,0为第一首
    public static int isShuffle = 2; //播放方式 0单曲循环，1列表循环，2真随机播放。

    //设置播放方式
    public static void setShuffle(int shuffle) {
        isShuffle = shuffle;

        mediaPlayer.setLooping(shuffle == 0);
    }

    public static void start() {
        if (!mediaPlayer.isPlaying()) {
            mediaPlayer.start(); // 开始播放
            EventBus.getDefault().post(3);
        }
    }

    public static void pause() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            EventBus.getDefault().post(4);
        }
    }

    public static void init() {
        //音乐播放结束，切歌，目前软件打开就会执行一次！
        Log.d("TAG", "init: "+ (mediaPlayer == null));

        mediaPlayer.setOnCompletionListener(mediaPlayer1 -> {
            Log.d("TAG", "onCreate: setOnCompletionListener");
            if (isShuffle == 1) {
                // 列表循环
                if (currentPosition < Music.pathList.size() - 1) {
                    currentPosition++;
                } else {
                    currentPosition = 0;
                }
            } else if (Music.isShuffle == 2) {
                // 随机播放
                Random random = new Random();
                int randomPosition = random.nextInt(Music.pathList.size());
                currentPosition = randomPosition;
            } else {
                return;
            }
            Music.playMusic();
            EventBus.getDefault().post(2);
        });
    }


    // 播放音乐 用的下面的 这种暂时没用到放着
    public static void playMusic(String path) {
        if (mediaPlayer != null) {
            mediaPlayer.reset();
        }
        try {
            mediaPlayer.setDataSource(path);  // 设置数据源
            mediaPlayer.prepare();             // 准备播放
            mediaPlayer.start();               // 开始播放
            EventBus.getDefault().post(1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //重新播放音乐，切歌
    public static void playMusic() {
        if (mediaPlayer != null) {
            mediaPlayer.reset();
        }
        try {
            mediaPlayer.setDataSource(pathList.get(currentPosition));  // 设置数据源
            mediaPlayer.prepare();             // 准备播放
            mediaPlayer.start();               // 开始播放

            EventBus.getDefault().post(1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //下一首
    public static void playNext() {
        switch (isShuffle) {
            case 1:
            case 0:
                currentPosition++;
                break;
            case 2:
                Random random = new Random();
                currentPosition = random.nextInt(pathList.size());
                break;
        }
        playMusic();
        EventBus.getDefault().post(2);
    }

    //上一首
    public static void playPrevious() {
        switch (isShuffle) {
            case 1:
            case 0:
                currentPosition--;
                break;
            case 2:
                Random random = new Random();
                currentPosition = random.nextInt(pathList.size());
                break;
        }
        playMusic();
        EventBus.getDefault().post(2);
    }


    public static void getMusicFiles() {
        // 使用ContentResolver查询音乐文件
        ContentResolver contentResolver = MyApp.getInstance().getContentResolver();
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        Cursor cursor = contentResolver.query(uri, null, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            // 获取列索引
            int titleColumn = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
            int idColumn = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
            int data = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);            //对应数据库的列号
            int display_name = cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME); //对应数据库的列号

            do {

                String music_name = cursor.getString(display_name);    //音频文件名,带.mp3
                String path = cursor.getString(data);            //音频文件路径
                long id = cursor.getLong(idColumn);
                String title = cursor.getString(titleColumn);//音频文件名,不带.mp3

                Log.d("TAG", "music_name: " + music_name + " path:" + path + " id:" + id + " title:" + title);
                if (!title.equals("tone") && !title.equals("au_uu_SzH34yR2")) {
                    // 添加到音乐文件列表
                    Music.nameList.add(title);
                    Music.pathList.add(path);
                }
            } while (cursor.moveToNext());
            cursor.close();
        }
    }


    //释放资源
    public static void release() {
        if (mediaPlayer != null) {
            mediaPlayer.release(); // 释放 MediaPlayer 资源
            mediaPlayer = null;
        }
    }
}
